<template>
  <div class="menu assetsMenu" v-if="userInfo.userName" @mouseover="hideSubmenu">
    <div class="caption" @click.stop="$router.push('/assets')" @mouseover="setScrollBar">
      <i class="icon"></i>
      <span class="text">{{lang.headerAssets}}</span>
      <i class="arrow"></i>
    </div>
    <div class="panel assets">

      <div class="head">
        <router-link class="recharge" :to="{path: '/assets'}">{{lang['Charging money']}} / {{lang['carry currency']}}</router-link>
        <p class="USDTotal">{{lang['total assets replacement']}}：{{formatNum(assetTotal, 2)}} USDT</p>
      </div>
      <div class="options">

      </div>
      <table class="list">
        <thead>
          <tr>
            <th>{{lang['currency surname']}}</th>
            <th>{{lang['available']}}</th>
            <th>{{lang['freeze']}}</th>
          </tr>
        </thead>
      </table>
      <div class="listWrap">
        <table class="list">
          <tbody>
            <tr v-for="item in assetsList" :id="item.ID" v-if="item.AssetsType !== 1">
              <td>
                <span>
                  <img :src="currencyImgUrl + item.Logo"/>
                </span>{{item.Symbol}}</td>
              <td>{{formatNum(item.AvailableAmount, item.Precision)}}</td>
              <td>{{formatNum(item.FreeAmount, item.Precision)}}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import EventBus from '@/service/EventBus.js'
import codeHandles from '@/service/Http/codeHandles.js'
import Decimal from '@/libs/decimal.min.js'
import commonFilter from '@/filters/common.js'

let openUSDResult = false
global.openUSDResult = openUSDResult

export default {
  props: [
    'lang',
    'userInfo'
  ],
  data () {
    return {
      totalBTC: '',
      assetTotal: 0,
      assetsList: [],
      pairs: [],
      defaultCurrencyID: '',
      refreshAssetsTimer: null,
      refreshAssetsInterval: 1 * 60 * 1000 // 1分钟
    }
  },
  methods: {
    // 隐藏head中的二级菜单，防止遮挡弹出框
    hideSubmenu:function(){
      this.$emit("hideSubmenu")
    },
    formatNum (val, prec) {
      return commonFilter.fillDecimal(commonFilter.currency(new Decimal(val).toFixed(10), 'USD', '', prec), prec)
    },
    getAssets () {
      return this.$http.post('CustomerAssets/GetAssets', {}, {
        isDisposeCode: false
      })
    },
    setAssets () {
      this.getAssets().then((res) => {
        if (res.isOk) {
          this.assetTotal = res.Data.TotalUSD
          this.totalBTC = res.Data.TotalBTC

          // 前端暂时修改顺序，找到BTC,排在BCH前面，已知条件是“货币ID不会变，顺序可能会变”，写出以下代码
          let list = res.Data.Assets || []
          // console.log(res.Data.Assets)
          // let BTCId = '1xx3-k3olkGgIwEiPqwXMw'
          // let BCHId = '8PqFnATs2U6oYPFxJjAooQ'
          // let BTCItem
          // for (let i = 0; i < list.length; i++) {
          //   if (list[i].ID === BTCId) {
          //     BTCItem = list.splice(i, 1)[0]
          //     break
          //   }
          // }
          // for (let j = 0; j < list.length; j++) {
          //   if (list[j].ID === BCHId) {
          //     list.splice(j, 0, BTCItem)
          //     break
          //   }
          // }

          this.assetsList = list
          // this.calaUSDTotal() // 计算资产折合

          EventBus.$emit('updateAssets', this.assetsList)
        }

        if (this.userInfo.userId) {
          res.StatusCode === '42011' && codeHandles['42011']()
          res.StatusCode === '42025' && codeHandles['42025']()
        }

        // 定时刷新资产总折合（根据行情）
        setTimeout(this.refreshAssets, this.refreshAssetsInterval)
      })
    },
    // 定时刷新
    refreshAssets () {
      clearTimeout(this.refreshAssetsTimer)
      this.getAssets().then((res) => {
        if (res.isOk) {
          this.assetTotal = res.Data.TotalUSD
          let list = res.Data.Assets || []
          this.assetsList = list
          EventBus.$emit('updateAssets', this.assetsList)
        }

        this.refreshAssetsTimer = setTimeout(this.refreshAssets, this.refreshAssetsInterval)
      })
    },
    setScrollBar () {
      // 滚动条
      this.$nextTick(() => {
        $('.panel.assets .listWrap').niceScroll({autohidemode: false}).resize()
      })
    }
    // 计算资产折合成美元，在初次载入时、交易对最新价更新时、资产更新时需要重新计算
    // calaUSDTotal () {
    //   // console.log('this.assetsList, this.pairs', this.assetsList.length, this.pairs.length)
    //   // 用此判断，适用在pairs、assetsList其中一方未加载的情况下
    //   if (!this.assetsList || !this.pairs || !this.assetsList.length || !this.pairs.length) return

    //   let founds = {} // 应对同时存在BCH/USD BCH/BTC这种情况，记录已经算过的BCH
    //   let totalUSD = new Decimal(0)
    //   for (let i = 0; i < this.assetsList.length; i++) {
    //     if (this.assetsList[i].ID === this.defaultCurrencyID) {
    //       totalUSD = new Decimal(totalUSD.add(this.assetsList[i].AvailableAmount).add(this.assetsList[i].FreeAmount).toFixed())
    //       global.openUSDResult && console.log('美元', this.assetsList[i].AvailableAmount, this.assetsList[i].FreeAmount, totalUSD.toFixed())
    //       continue
    //     }
    //     for (let j = 0; j < this.pairs.length; j++) {
    //       if (
    //         !founds[this.assetsList[i].ID] &&
    //         this.assetsList[i].ID === this.pairs[j].SellerCoinID &&
    //         this.pairs[j].BuyerCoinID === this.defaultCurrencyID
    //       ) {
    //         global.openUSDResult && console.log(this.assetsList[i].AssetsCode, this.pairs[j].Newest, this.assetsList[i].AvailableAmount, this.assetsList[i].FreeAmount, this.pairs[j].Newest * (this.assetsList[i].AvailableAmount + this.assetsList[i].FreeAmount))
    //         totalUSD = new Decimal(totalUSD.add(this.pairs[j].Newest * (this.assetsList[i].AvailableAmount + this.assetsList[i].FreeAmount)))
    //         founds[this.assetsList[i].ID] = true
    //       }
    //     }
    //   }
    //   global.openUSDResult && console.log('totalUSD', totalUSD.toFixed())
    //   this.assetTotal = totalUSD.toFixed()
    // }
  },
  created () {
    EventBus.$on('sendPairsToTrade', (pairs, defaultCurrencyID) => {
      this.pairs = pairs
      this.defaultCurrencyID = defaultCurrencyID
      // this.calaUSDTotal()
    })

    EventBus.$on('pushAssets', (assetsList) => {
      for (let i = 0; i < assetsList.length; i++) {
        for (let j = 0; j < this.assetsList.length; j++) {
          if (assetsList[i].ID === this.assetsList[j].ID) {
            this.assetsList[j].AvailableAmount = assetsList[i].AvailableAmount
            this.assetsList[j].FreeAmount = assetsList[i].FreeAmount
          }
        }
      }
      // this.calaUSDTotal()

      EventBus.$emit('updateAssets', this.assetsList)
    })
  },
  mounted () {
    this.userInfo.userName && this.setAssets() // 有登录才获取资产
  },
  beforeDestroy () {
    clearTimeout(this.refreshAssetsTimer)
  }
}
</script>

<style lang="less">
@import "./../../../mixins.less";

.tradingPage, .ctcPage {

  .pageHead {

    .menu.assetsMenu {
      margin-right: -1px;

      &:hover {

        >.caption {

          .icon {
            background: url(../../../assets/images/head/menu-assets-active.png) no-repeat;
          }
        }
      }

      .caption {
        font-weight: normal;

        .icon {
          background: url(../../../assets/images/head/menu-assets.png) no-repeat;
        }
      }
      .panel {
        padding-bottom: 10px;
      }
    }

    .menu.userMenu {

      .caption {
        font-weight: normal;
      }
    }
  }

  .assets {
    margin-left: -150px;
    padding-top: 16px;
    width: 420px;
    white-space: nowrap;

    .head {
      padding-bottom: 10px;
    }

    .USDTotal {
      margin-left: 16px;
    }
    .recharge {
      float: right;
      margin-right: 16px;
      color: @tradingLinkActiveColor;
    }
    .listWrap {
      max-height: 400px;
    }
    .list {

      thead {
        border-bottom: 1px solid #1a1f25;
      }

      th, td {
        line-height: 36px;
        text-align: right;

        &:nth-of-type(1) {
          padding-left: 16px;
          width: 20%;
          text-align: left;
        }
        &:nth-of-type(2) {
          width: 36%;
        }
        &:nth-of-type(3) {
          width: 44%;
          padding-right: 16px;
        }
      }
      tbody {

        tr {
          height: 36px;
          line-height: 36px;
          border-bottom: 1px solid #1a1f25;

          &:last-of-type {
            border-bottom: 0;
          }
        }
      }
      td {
        text-align: right;

        &:first-of-type {
          padding-left: 16px;
          text-align: left;
        }

        &:last-of-type {
          padding-right: 16px;
        }

        span {
          display: inline-block;
          margin-right: 8px;
          width: 20px;
          height: 8px;20
          text-align: center;
        }

        img {
          position: relative;
          top: -2px;
          vertical-align: middle;
          height: 20px;
        }
      }
    }
  }
}
</style>
